package com.example.security.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.example.security.demo.dto.UserDto;
import com.example.security.demo.service.TokenService;
import com.example.security.demo.service.UserService;
import com.example.security.demo.vo.R;
import com.example.security.demo.vo.UserVo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhanpengguo
 * @date 2019-10-15 10:19
 */
@RestController
@AllArgsConstructor
@RequestMapping("user")
public class UserController {

    private final UserService userService;

    private final TokenService tokenService;

    @PostMapping("/login")
    public String login() {
        return "登录成功";
    }

    @PostMapping("/register")
    public R register(@RequestBody UserVo userVo) {
        if (userVo == null || userVo.getUsername() == null || userVo.getPassword() == null) {
            return new R(new Throwable("用户名和密码不能为空"));
        }
        userService.save(userVo);
        return new R("注册成功");
    }

    @PostMapping("/checkToken")
    public R checkToken(String token, String username) {
        if (StrUtil.isEmpty(token) || StrUtil.isEmpty(username)) {
            return new R(new Throwable("用户名或token无效"));
        }
        UserDto userDto = tokenService.queryUserByToken(token);
        if (!StrUtil.equals(username, userDto.getUsername())) {
            return new R(new Throwable("token不正确"));
        }
        return new R("验证通过");
    }
}
